/**
 * 蚂蚁搬家分析器 - 对象中心化版本
 * 检测多笔小额交易累计成大额的异常行为
 */

class SmurfingAnalyzer extends BaseAnalyzer {
  constructor(caseId, targetSubject = null) {
    super(caseId, targetSubject);
    this.name = '蚂蚁搬家';
    this.description = '检测多笔小额交易在短时间内累计成大额的拆分行为';
  }

  async analyze(params = {}) {
    const timeWindowDays = params.timeWindowDays || 7;
    const minTotalAmount = params.minTotalAmount || 100000;
    const maxSingleAmount = params.maxSingleAmount || 10000;
    const minTransCount = params.minTransCount || 5;

    const accountFilter = this.getBankAccountFilter();

    const sql = `
            SELECT 
                account_card,
                customer_name,
                counterparty_name,
                debit_credit_flag,
                COUNT(*) as trans_count,
                SUM(ABS(transaction_amount)) as total_amount,
                MIN(transaction_time) as first_time,
                MAX(transaction_time) as last_time,
                CAST((julianday(MAX(transaction_time)) - julianday(MIN(transaction_time))) AS REAL) as days_span
            FROM bank_transactions
            WHERE case_id = ?
                AND ABS(transaction_amount) <= ?
                ${accountFilter}
            GROUP BY account_card, counterparty_name, debit_credit_flag
            HAVING trans_count >= ?
                AND total_amount >= ?
            ORDER BY total_amount DESC
            LIMIT 100
        `;

    const result = await this.runQuery(sql, [
      this.caseId,
      maxSingleAmount,
      minTransCount,
      minTotalAmount
    ]);

    if (!result.success) {
      return this.createResult('smurfing', this.name, [], '查询失败: ' + result.message, 'danger');
    }

    const data = result.data.filter(row => row.days_span <= timeWindowDays);
    const summary = data.length > 0
      ? `检测到 ${data.length} 组蚂蚁搬家交易，累计金额 ¥${this.formatAmount(data.reduce((sum, r) => sum + r.total_amount, 0))}`
      : '未检测到蚂蚁搬家交易模式';

    const level = data.length > 5 ? 'danger' : (data.length > 0 ? 'warning' : 'info');

    return this.createResult('smurfing', this.name, data, summary, level);
  }

  renderResult(data) {
    if (!data || data.length === 0) {
      return '<div class="empty-result" style="padding:40px; text-align:center; color:#999;">✓ 未发现蚂蚁搬家异常</div>';
    }

    let html = `
      <div class="result-summary" style="padding:15px; background:#fef0f0; border-left:4px solid #f56c6c; margin-bottom:15px;">
        <strong>🐜 发现 ${data.length} 组蚂蚁搬家交易</strong>
        <p style="margin:5px 0 0; font-size:0.9rem;">多笔小额交易累计成大额，疑似拆分逃避监管</p>
      </div>
      
      <table class="analysis-result-table" style="width:100%; border-collapse:collapse; font-size:0.9rem;">
        <thead style="background:#f5f7fa;">
          <tr>
            <th style="padding:10px; border:1px solid #e0e0e0;">账号/户名</th>
            <th style="padding:10px; border:1px solid #e0e0e0;">对方账户</th>
            <th style="padding:10px; border:1px solid #e0e0e0; text-align:center;">交易次数</th>
            <th style="padding:10px; border:1px solid #e0e0e0; text-align:right; background:#fff3cd;">累计金额</th>
            <th style="padding:10px; border:1px solid #e0e0e0;">时间跨度(天)</th>
          </tr>
        </thead>
        <tbody>
    `;

    data.forEach((row, index) => {
      const rowStyle = index % 2 === 0 ? 'background:#fafafa;' : '';
      html += `<tr style="${rowStyle}">`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0;">${row.customer_name}<br><small style="color:#909399; font-family:monospace;">${row.account_card}</small></td>`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0;">${row.counterparty_name || '-'}</td>`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0; text-align:center; font-weight:bold;">${row.trans_count}</td>`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0; text-align:right; color:#f56c6c; font-weight:bold;">¥${this.formatAmount(row.total_amount)}</td>`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0;">${row.days_span.toFixed(1)}</td>`;
      html += '</tr>';
    });

    html += '</tbody></table>';
    return html;
  }
}

window.SmurfingAnalyzer = SmurfingAnalyzer;
